package com.example.triangle;

import android.annotation.SuppressLint;
import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.util.DisplayMetrics;
import android.util.Log;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyGLRenderer implements GLSurfaceView.Renderer {
    // Used to load the 'triangle' library on application startup.
    static {
        System.loadLibrary("triangle");
    }
    private Triangle mTriangle;
    private int screenWidth, screenHeight; // 屏幕宽度和高度
    boolean useNative;
    public MyGLRenderer(Context context, boolean useNative)
    {
        // 获取屏幕宽度和高度
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        this.useNative=useNative;
    }
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);//清空屏幕
        mTriangle = new Triangle();//创建一个形状
        init();
    }
    int frameCount=0;
    long frameStartTime=0;
    int fps=0;
    @Override
    public void onDrawFrame(GL10 gl) {
        // 在渲染每一帧前计算FPS
        long currentTime = System.currentTimeMillis();
        frameCount++;
        if (currentTime - frameStartTime >= 1000) { // 每秒更新一次FPS
            fps = frameCount;
            frameCount = 0;
            frameStartTime = currentTime;
            // 绘制FPS文本
            drawText("FPS: " + fps, screenWidth - 150, 50);
        }

        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);//清空屏幕
        if(!useNative)
             mTriangle.draw();//执行形状的绘图方法
        else
             drawTriangle();
    }


    // 在指定位置绘制文本
    private void drawText(String text, float x, float y) {
        // 省略具体实现
        Log.i("Render","FPS "+text);
    }
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }
    public static int loadShader(int type, String shaderCode) {
        int shader = GLES20.glCreateShader(type);
        if (shader == 0) {
            Log.e("MyGLRenderer", "Failed to create shader");
            return 0;
        }
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);
        return shader;
    }
    public native void drawTriangle();
    public native void init();
}
